#include "cubeshader.h"
#include <math.h>
#include <QDir>

QVector2D translations[100];

CubeShader::CubeShader(QObject *parent)
    :BaseShader(parent)
{
    m_file_vert = ":/chest.vert";
    m_file_frag = ":/chest.frag";

//    ourModel = new MyModel(QDir::currentPath() + "/../models/untitled.obj");
}

void CubeShader::initializeGL()
{
    BaseShader::initializeGL();

    aPos = m_program->attributeLocation("aPos");
    aColor = m_program->attributeLocation("aColor");

    float quadVertices[] = {
        // 位置          // 颜色
        -0.05f,  0.05f,  1.0f, 0.0f, 0.0f,
         0.05f, -0.05f,  0.0f, 1.0f, 0.0f,
        -0.05f, -0.05f,  0.0f, 0.0f, 1.0f,

        -0.05f,  0.05f,  1.0f, 0.0f, 0.0f,
         0.05f, -0.05f,  0.0f, 1.0f, 0.0f,
         0.05f,  0.05f,  0.0f, 1.0f, 1.0f
    };

//    GLuint vao;
//    GLuint vbo;

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(aPos);
    glEnableVertexAttribArray(aColor);

    glVertexAttribPointer(aPos, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, BUFFER_OFFSET(0));
    glVertexAttribPointer(aColor, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, BUFFER_OFFSET(sizeof(GLfloat) * 2));

    int index = 0;
    float offset = 0.1f;
    for(int y = -10; y < 10; y += 2)
    {
        for(int x = -10; x < 10; x += 2)
        {
            QVector2D translation;
            translation.setX((float)x / 10.0f + offset);
            translation.setY((float)y / 10.0f + offset);
            translations[index++] = translation;
        }
    }

    unsigned int instanceVBO;
    glGenBuffers(1, &instanceVBO);
    glBindBuffer(GL_ARRAY_BUFFER, instanceVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(QVector2D) * 100, &translations[0], GL_STATIC_DRAW);

    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), BUFFER_OFFSET(0));

    glVertexAttribDivisor(2, 1); //在渲染一个新实例的时候更新顶点属性
}

void CubeShader::paintGL()
{
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glClearColor(0.05f, 0.05f, 0.05f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//    glEnable(GL_DEPTH_TEST);

    m_program->bind();
    glBindVertexArray(vao);

//    for(unsigned int i = 0; i < 100; i++)
//    {
//        m_program->setUniformValue(QString("offsets[" + QString::number(i) + "]").toUtf8().data(), translations[i]);
//    }

    glDrawArraysInstanced(GL_TRIANGLES, 0, 6, 100);

    glBindVertexArray(0);
    m_program->release();
}
